<template>
    <div class="clearfix fb-control"
         v-if="unit.visible">
        <label class="col-sm-2 control-label">{{ unit.label }}</label>
        <div class="col-sm-10">
            {{ unit.padLeft }}
            <input :id="unit.unitGid" />
            {{ unit.padRight }}
            <span class="help-block" v-if="unit.helpText">{{ unit.helpText }}</span>
        </div>
    </div>
</template>
<script>
    import { mapGetters } from 'vuex'
    import _ from 'lodash'
    export default {
        name: 'NumericTextboxUnit',
        props: ['unit'],
        data () {
            return {}
        },
        computed: {
            ...mapGetters({
                locale: 'locale'
            })
        },
        mounted () {
            this.destroyUnit().then(() => {
                this.initUnit()
            })
        },
        beforeDestroy () {
            this.destroyUnit()
        },
        methods: {
            initUnit () {
                const kendoNumericTextBox = $('#' + this.unit.unitGid).kendoNumericTextBox({
                    culture: _.isNil(this.unit.culture) ? this.locale : this.unit.culture,
                    decimals: _.isNaN(this.unit.decimals) ? 2 : this.unit.decimals,
                    factor: _.isNaN(this.unit.factor) ? 1 : this.unit.factor,
                    format: _.isNil(this.unit.format) ? 'n' : this.unit.format,
                    min: _.isNaN(this.unit.min) ? null : this.unit.min,
                    max: _.isNaN(this.unit.max) ? null : this.unit.max,
                    round: _.isNil(this.unit.round) ? true : this.unit.round,
                    spinners: _.isNil(this.unit.spinners) ? true : this.unit.spinners,
                    step: _.isNaN(this.unit.step) ? 1 : this.unit.step,
                    value: _.isNaN(this.unit.defaultValue) ? null : this.unit.defaultValue
                }).data('kendoNumericTextBox')

                if (!_.isNil(this.unit.width)) {
                    const reg = /(\d+)(px|%|em|in|pt)$/gi
                    if (reg.test(this.unit.width)) {
                        kendoNumericTextBox.wrapper.css('width', this.unit.width)
                    }
                }
            },
            /**
             * 销毁控件实例
             */
            destroyUnit () {
                let unit
                if (!_.isEmpty(this.unit)) {
                    unit = $('#' + this.unit.unitGid).data('kendoNumericTextBox')
                }

                return new Promise((resolve) => {
                    if (!_.isEmpty(unit)) {
                        unit.destroy()
                    }
                    resolve()
                })
            }
        }
    }
</script>